package com.amtf.datafile3.core.fil.render;

import java.text.Format;
import java.util.HashMap;
import java.util.Map;

import com.amtf.datafile3.DataField;
import com.amtf.datafile3.DataFieldRender;
import com.amtf.datafile3.DataFieldType;
import com.amtf.datafile3.core.std.AbsDataFieldRender;

public class FilDataFieldRender extends AbsDataFieldRender {
	private final String fill = " ";
	private int length = 0;
	private final Map<Integer, String> fills = new HashMap<Integer, String>();

	public FilDataFieldRender(int length) {
		super(null);
	}

	public FilDataFieldRender(int length, Format format) {
		super(format);
		this.length = length;
	}

	public String rending(DataField value) {
		if (value.getValue() != null) {
			String tmpValue = null;
			if (format != null) {
				tmpValue = format.format(value.getValue());
			} else {
				tmpValue = value.getValue().toString();
			}

			int spaceCount = length - tmpValue.length();

			return tmpValue + getFillString(spaceCount);
		} else {
			DataFieldType tp = value.getDefinition().getType();
			return getFillString(tp.getTotalLength());
		}
	}

	public String getFillString(int spaceCount) {
		String padString = fills.get(spaceCount);
		if (padString == null) {
			padString = "";
			for (int i = 0; i < spaceCount; i++) {
				padString += fill;
			}
			fills.put(spaceCount, padString);
		}

		return padString;
	}

	@Override
	public DataFieldRender clone() {
		FilDataFieldRender newObj = new FilDataFieldRender(length, format);
		newObj.fills.putAll(this.fills);
		return newObj;
	}
	
	public int getLength() {
		return length;
	}

	public void setLength(int length) {
		this.length = length;
	}

}
